<!--
 * @Description: 社群商品添加
 * @Author: liyujie
 * @Date: 2021/04/14
 * @Last Modified by: liyujie
 * @Last Modified time: 2021/04/14
-->
<template>
    <div class="wrapper group-goods-add">
        <div class="content-wrapper">
            <!-- header -->
            <div class="header">
                <div class="header-title">
                    社群专享价 - 添加商品
                </div>
                <div class="header-content">
                    <el-button
                        type="primary"
                        size="medium"
                        style="width: 104px"
                        @click="$refs.goodsSelect.show(2, requestUrl, typeList, 1)"
                    >
                        {{ this.ruleForm.tableData.length ? '继续添加' : '选择商品' }}
                    </el-button>
                    <el-button
                        type="primary"
                        size="medium"
                        style="width: 104px;margin-left: 32px"
                        @click="goodsImportDialog = true"
                    >
                        导入商品
                    </el-button>
                </div>
            </div>
            <div class="bg-line"/>
            <!-- /header -->

            <el-form
                :model="ruleForm"
                :rules="rules"
                ref="ruleForm"
                v-if="ruleForm.tableData.length"
            >
                <div class="goods-wrapper">
                    <el-table
                        :data="ruleForm.tableData"
                        style="width: 100%;"
                        class="data-table product"
                        @selection-change="handleSelectAll($event)"
                    >
                        <el-table-column
                            type="selection"
                            align="center"
                            width="48"
                        >
                            <template slot-scope="scope">
                                <div
                                    v-for="item in scope.row.product_list"
                                    :key="item.product_no"
                                    class="table-item"
                                >
                                    <el-checkbox
                                        v-model="item.check_status"
                                        :true-label="1"
                                        :false-label="0"
                                        style="margin-bottom: 12px"
                                    />
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column
                            width="280"
                            label="商品信息"
                            fixed="left"
                        >
                            <template slot-scope="scope">
                                <div class="goods-info">
                                    <img
                                        :src="scope.row.goods_cover"
                                        class="goods-cover"
                                        @click="fnShowPreview(scope.row.goods_cover)"
                                    >
                                    <div class="info">
                                        <div class="goods-info__title">
                                            {{ scope.row.goods_title }}
                                        </div>
                                        <div class="goods-info__no">
                                            商品编号：{{ scope.row.goods_no }}
                                        </div>
                                        <div class="goods-info__shop-title">
                                            店铺名称：{{ scope.row.shop_title }}
                                        </div>
                                    </div>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="限购数量"
                            width="100"
                            align="center"
                        >
                            <template slot-scope="scope">
                                <el-form-item
                                    :prop="`tableData[${scope.$index}].buy_limit_count`"
                                    :rules="rules.buy_limit_count"
                                >
                                    <el-input
                                        v-model="scope.row.buy_limit_count"
                                        size="small"
                                        placeholder="-1不限购"
                                        style="width: 80px;"
                                    />
                                </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="佣金比例"
                            width="100"
                            align="center"
                        >
                            <template slot-scope="scope">
                                <el-form-item
                                    :prop="`tableData[${scope.$index}].commission_rate`"
                                    :rules="rules.commission_rate"
                                >
                                    <el-input
                                        v-model="scope.row.commission_rate"
                                        size="small"
                                        style="width: 80px;"
                                    >
                                        <span
                                            slot="suffix"
                                            style="margin-right: 5px"
                                        >%</span>
                                    </el-input>
                                </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="商品规格"
                            width="240"
                        >
                            <template slot-scope="scope">
                                <div
                                    class="table-item sku"
                                    v-for="(item) in scope.row.product_list"
                                    :key="item.product_no"
                                    :style="`color:${item.check_status ? '#1890FF' : ''};cursor: pointer`"
                                    @click="handleChecked(item)"
                                >
                                    <el-form-item>
                                        <el-tooltip
                                            effect="dark"
                                            :content="item.spec_list | filterSpec"
                                            placement="top"
                                        >
                                            <span>{{ item.spec_list | filterSpec }}</span>
                                        </el-tooltip>
                                    </el-form-item>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="原售价"
                            align="center"
                        >
                            <template slot-scope="scope">
                                <div
                                    class="table-item"
                                    v-for="item in scope.row.product_list"
                                    :key="item.product_no"
                                >
                                    <el-form-item>
                                        ￥{{ item.product_price }}
                                    </el-form-item>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="活动专享价"
                            width="120"
                            align="center"
                        >
                            <template slot-scope="scope">
                                <div
                                    class="table-item"
                                    v-for="(item, index) in scope.row.product_list"
                                    :key="item.product_no"
                                >
                                    <el-form-item
                                        :prop="`tableData[${scope.$index}].product_list[${index}]`"
                                        :rules="rules.price"
                                    >
                                        <el-input
                                            v-model="item.price"
                                            size="small"
                                            style="width: 90px;"
                                            :disabled="!item.check_status"
                                            @click.native="clickDisableInput(item)"
                                        >
                                            <span
                                                slot="suffix"
                                                style="margin-right: 5px"
                                            >元</span>
                                        </el-input>
                                    </el-form-item>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="活动库存"
                            align="left"
                            width="220"
                        >
                            <template slot-scope="scope">
                                <div
                                    class="table-item"
                                    v-for="(item,index) in scope.row.product_list"
                                    :key="item.product_no"
                                    style="justify-content: flex-start"
                                >
                                    <div
                                        style="display: flex; align-items: center;justify-content: center"
                                    >
                                        <el-select
                                            v-model="item.stock_type"
                                            :style="{width: item.stock_type === 1 ? '136px' : '96px',marginBottom: '10px'}"
                                            size="small"
                                            :disabled="!item.check_status"
                                            @change="handleStockTypeChange($event, item)"
                                            @click.native="clickDisableInput(item)"
                                        >
                                            <el-option
                                                label="同步商家库存"
                                                :value="1"
                                            />
                                            <el-option
                                                label="自定义"
                                                :value="2"
                                            />
                                        </el-select>
                                        <el-form-item
                                            :prop="`tableData[${scope.$index}].product_list[${index}]`"
                                            :rules="rules.stock"
                                            v-if="item.stock_type === 2"
                                        >
                                            <el-input
                                                oninput="value = value.replace(/[^\d]/g,'')"
                                                placeholder="活动库存"
                                                v-model.number="item.stock"
                                                style="width: 84px;margin-left: 12px"
                                                size="small"
                                                :disabled="!item.check_status"
                                                @click.native="clickDisableInput(item)"
                                            />
                                        </el-form-item>
                                    </div>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="商家库存"
                            align="center"
                        >
                            <template slot-scope="scope">
                                <div
                                    class="table-item"
                                    v-for="item in scope.row.product_list"
                                    :key="item.product_no"
                                >
                                    <el-form-item>
                                        {{ item.product_stock }}
                                    </el-form-item>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="是否平台补贴"
                            align="center"
                            width="110"
                        >
                            <template slot-scope="scope">
                                <div
                                    class="table-item"
                                    v-for="(item) in scope.row.product_list"
                                    :key="item.product_no"
                                >
                                    <div
                                        style="display: flex; align-items: center;justify-content: center"
                                    >
                                        <el-form-item style="margin-top: -4px">
                                            <el-select
                                                v-model="item.shop_subsidy_enable"
                                                size="small"
                                                style="width: 100px"
                                                @change="handleSubsidyChange($event, item)"
                                                :disabled="!item.check_status"
                                                @click.native="clickDisableInput(item)"
                                            >
                                                <el-option
                                                    label="平台补贴"
                                                    :value="1"
                                                />
                                                <el-option
                                                    label="商家全部补贴"
                                                    :value="0"
                                                />
                                                <el-option
                                                    label="商家部分补贴"
                                                    :value="2"
                                                />
                                            </el-select>
                                        </el-form-item>
                                    </div>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="商家补贴金额"
                            align="center"
                            width="130"
                        >
                            <template slot-scope="scope">
                                <div
                                    class="table-item"
                                    v-for="(item,index) in scope.row.product_list"
                                    :key="item.product_no"
                                >
                                    <div
                                        style="display: flex; align-items: center;justify-content: center"
                                    >
                                        <el-form-item
                                            :prop="`tableData.${scope.$index}.product_list[${index}]`"
                                            :rules="rules.shop_subsidy_money_by_shop"
                                            style="margin-top: -4px"
                                        >
                                            <el-input
                                                v-model="item.shop_subsidy_money_by_shop"
                                                placeholder="商家补贴金额"
                                                size="small"
                                                clearable
                                                style="width: 120px"
                                                :disabled="!item.check_status || item.shop_subsidy_enable !== 2"
                                                @click.native="clickDisableInput(item)"
                                            />
                                        </el-form-item>
                                    </div>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="活动时间"
                            width="350"
                            align="center"
                        >
                            <template slot-scope="scope">
                                <div class="table-item">
                                    <el-form-item
                                        :prop="`tableData[${scope.$index}].dateTimeRange`"
                                        :rules="rules.dateTimeRange"
                                    >
                                        <el-date-picker
                                            v-model="scope.row.dateTimeRange"
                                            type="datetimerange"
                                            range-separator="-"
                                            start-placeholder="开始日期"
                                            end-placeholder="结束日期"
                                            :default-time="['00:00:00', '23:59:59']"
                                            size="small"
                                            style="width: 330px"
                                            value-format="timestamp"
                                            @change="handleDateChange(scope.row)"
                                        />
                                    </el-form-item>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="操作"
                            align="center"
                        >
                            <template slot-scope="scope">
                                <div class="table-item">
                                    <el-form-item>
                                        <el-button
                                            type="primary"
                                            size="mini"
                                            @click="deleteGoods(scope.$index)"
                                        >
                                            删除
                                        </el-button>
                                    </el-form-item>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </el-form>
            <div
                class="empty-view"
                v-else
            >
                <div class="empty-img">
                    <img
                        src="@/assets/image/empty-goods.png"
                        alt=""
                    >
                </div>
                <div class="empty-text">暂未添加商品，点击左上角按钮进行添加商品</div>
            </div>
            <div class="submit-view">
                <el-button
                    type="primary"
                    size="medium"
                    style="width: 120px"
                    :loading="loading"
                    @click="handleSubmit"
                >
                    确认提交
                </el-button>
            </div>
        </div>
        <!--商品选择弹窗-->
        <goods-select
            ref="goodsSelect"
            from-type="group_goods"
            @change="handleSelectGoods($event, setIndex)"
        />
        <!-- 导入商品 -->
        <goods-import
            :visible.sync="goodsImportDialog"
            :request-url="requestUrl"
            :page-size="100"
            @change="handleSelectGoods($event.list)"
        />
        <!-- 图片预览 -->
        <img-preview
            ref="preview"
        />

        <!-- 预算提示弹窗 -->
        <show-dialog
            ref="showDialog"
            :dialog="showDialog"
            :width="360"
            :cancel-text="'取消'"
            :confirm-text="'确定'"
            :title="'温馨提示'"
            :content="`当前新人专区的平台补贴支出在计划时间${ '2021/5/24-2021/6/24' }已无预算，暂无法添加新人专区商品`"
            @close="showDialog = false"
            @emit="() => {
                this.$router.push({
                    name: 'groupGoodsList'
                });
            }"
        />
    </div>
</template>

<script>
import showDialog from '@/components/common/dialog.vue';
import { back } from '@/mixin/back';
import { deepClone } from "@/assets/js/utils";
import ImgPreview from "@/components/common/img-preview";
import GoodsSelect from "@/components/goods/goods-select";
import GoodsImport from "@/components/goods/goods-import";
const numberReg = /(?:^[1-9]([0-9]+)?(?:\.[0-9]{1,2})?$)|(?:^(?:0)$)|(?:^[0-9]\.[0-9](?:[0-9])?$)/;

export default {
    name: 'AdventGoodsAdd',
    mixins: [back],
    components: {GoodsImport, GoodsSelect, ImgPreview, showDialog},
    data() {
        const validatePrice = (rule, value, callback) => {
            if(value.check_status && !value.price) {
                callback(new Error('请填写活动价'));
            } else if(value.price && !numberReg.test(value.price)) {
                callback(new Error('活动价必须未数字'));
            } else {
                callback();
            }
        };
        const validateStock = (rule, value, callback) => {
            if(value.check_status && value.stock === '') {
                callback(new Error('请填写库存'));
            } else if(value.stock && !numberReg.test(value.stock)) {
                callback(new Error('库存必须未数字'));
            } else {
                callback();
            }
        };
        const validateSubsidy = (rule, value, callback) => {
            if(value.check_status && value.shop_subsidy_money_by_shop === '') {
                callback(new Error('请填写补贴金额'));
            } else if(value.shop_subsidy_money_by_shop && !numberReg.test(value.shop_subsidy_money_by_shop)) {
                callback(new Error('金额必须未数字'));
            } else {
                callback();
            }
        };
        const validateDate = (rule, value, callback) => {
            if(!value || !value.length) {
                callback(new Error('请选择活动时间'));
            } else {
                callback();
            }
        };

        return {
            requestUrl: '/student/shop_goods%5Cget_list_for_select',
            typeList: [{label: '自营', value: 1}],
            ruleForm: {
                tableData: []
            },
            rules: {
                buy_limit_count: [
                    { required: true, message: '请填写限购数量', trigger: 'blur' },
                ],
                commission_rate: [
                    { required: true, message: '请输入佣金', trigger: 'blur' },
                    { pattern: numberReg, message: '佣金须为数字', trigger: 'blur' }
                ],
                price: [
                    {validator: validatePrice, trigger: 'blur'}
                ],
                stock: [
                    {validator: validateStock, trigger: 'blur'}
                ],
                shop_subsidy_money_by_shop: [
                    {validator: validateSubsidy, trigger: 'blur'}
                ],
                dateTimeRange: [
                    {validator: validateDate, trigger: 'change'}
                ],
            },
            // 重新选择商品的index
            setIndex: 0,
            goodsImportDialog: false,
            loading: false,
            showDialog: false
        };
    },
    computed: {},
    watch: {},
    filters: {
        filterSpec (val) {
            if(!val) return '';
            let str = '';

            val.forEach(el => {
                str += el.spec_name + ':' + el.spec_value + '；';
            });
            return str;
        }
    },
    mounted() {
        this.init();
    },

    methods: {
        /**
         * 初始化
         */
        init() {
            this.$store.commit('SET_HEADER', [{title: "APP后台"}, {title: '商城'}, {title: '社群专享价', path: '/student/group-goods-list'}, {title: '添加商品'}]);
            this.authResult = this.$route.meta.authResult;
        },

        /**
         * 路由跳转
         * @param routeName
         * @param query
         */
        handleRoute(routeName, query) {
            this.$router.push({
                name: routeName,
                query
            });
        },

        /**
         * @description 过滤函数
         */
        emptyFormatter(row, column, val) {
            if (!val) return '--';
            return val;
        },

        /**
         * 预览图片
         * @param   {String}    images      //单图预览
         * @param   {Array}     images      //多图预览
         * @param index
         */
        fnShowPreview(images, index) {
            if (images && Object.prototype.toString.call(images) == '[object String]') {
                this.$refs.preview.show([
                    images
                ]);
            } else if (images && Object.prototype.toString.call(images) == '[object Array]') {
                this.$refs.preview.show(images, index);
            } else {
                this.$message({
                    type: 'warning',
                    message: '图片类型错误'
                });
            }
        },

        /**
         * 选择库存类型
         * @param val
         * @param skuItem
         */
        handleStockTypeChange(val, skuItem) {
            if(val === 1) {
                this.$set(skuItem, 'stock', -1);
            } else {
                this.$set(skuItem, 'stock', 0);
            }
        },

        /**
         * 是否平台补贴
         * @param val
         * @param skuItem
         */
        handleSubsidyChange(val, skuItem) {
            if(val !== 2) {
                this.$set(skuItem, 'shop_subsidy_money_by_shop', 0);
            }
        },

        /**
         * 选择商品
         * @param data
         * @param index
         */
        handleSelectGoods(data, index) {
            let dataList = deepClone(data).map(item => {
                item.buy_limit_count = -1;
                item.commission_rate = '';
                item.dateTimeRange = [];
                item.activity_start_time = '';
                item.activity_end_time = '';
                item.product_list.forEach(product => {
                    product.stock_type = 1;
                    product.stock = -1;
                    product.price = '';
                    product.check_status = 0;
                    product.shop_subsidy_enable = 1;
                    product.shop_subsidy_money_by_shop = 0;
                });
                return {...item};
            });

            this.ruleForm.tableData = [...this.ruleForm.tableData, ...this.checkGoodsRepeat(dataList)];
        },

        /**
         * 过滤重复商品
         */
        checkGoodsRepeat(goodsList) {
            this.ruleForm.tableData.forEach(item => {
                goodsList.forEach((goods, index) => {
                    if(item.goods_no === goods.goods_no) {
                        goodsList.splice(index, 1);
                    }
                });
            });
            return goodsList;
        },

        /**
         * 删除商品
         * @param index
         */
        deleteGoods(index) {
            this.ruleForm.tableData.splice(index, 1);
        },

        /**
         * 点击禁用的input
         * @param row
         */
        clickDisableInput(row) {
            if(!row.check_status) {
                this.$message.warning('请勾选该规格');
            }
        },

        /**
         * 全选
         * @param selection
         * @param index
         */
        handleSelectAll(selection, index) {
            this.ruleForm.tableData.forEach(item => {
                item.product_list.forEach(subItem => {
                    this.$set(subItem, 'check_status', selection.length ? 1 : 0);
                });
            });
        },

        /**
         * 提交
         */
        handleSubmit() {
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    this.loading = true;
                    let params = deepClone(this.ruleForm.tableData);

                    this.$post('/student/shop_tool_group_goods%5Cbatch_add', {goods_json: JSON.stringify(params)} ,resp=>{
                        if (resp.code === 1) {
                            if(resp.data.result === 1) {
                                this.handleRoute('groupGoodsList');
                                this.$notify({
                                    title: '提示',
                                    type: 'success',
                                    message: '保存成功'
                                });
                            } else {
                                this.$zdConfirm(`当前社群专享价商品的平台补贴支出${resp.data.result === -1 ? '不在财控计划时间内' : '在计划时间已无预算'} ，暂无法添加社群专享价商品，如需要增加预算，请联系平台财务人员。`, '温馨提示', {
                                    confirmButtonText: '知道了',
                                    hasCancelButton: false,
                                    type: 'warning'
                                }).then(() => {});
                            }
                        } else {
                            this.$notify({
                                title: '提示',
                                type: 'warning',
                                message: resp.msg
                            });
                        }
                        this.loading = false;
                    });
                }
            });
        },

        /**
         * 点击规格选中当前规格
         * @param skuItem
         */
        handleChecked(skuItem) {
            this.$set(skuItem, 'check_status', skuItem.check_status ? 0 : 1);
        },

        /**
         * 选择时间改变
         * @param row
         */
        handleDateChange(row) {
            row.activity_start_time = row.dateTimeRange ? row.dateTimeRange[0] / 1000 : '';
            row.activity_end_time = row.dateTimeRange ? row.dateTimeRange[1] / 1000 : '';
        }
    }
};
</script>

<style lang="less" scoped>
.wrapper {
    width: 100%;
    padding-bottom: 78px;
    .content-wrapper {
        display: flex;
        height: calc(100% - 24px);
        flex-direction: column;
        margin: 12px;
        box-sizing: border-box;
        background: #fff;
        .submit-view {
            width: 100%;
            height: 68px;
            background: #FFFFFF;
            box-shadow: 0px -1px 4px 0px rgba(0, 0, 0, 0.1);
            position: absolute;
            bottom: 0;
            left: 0;
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 9;
            padding-left: 210px;
        }

        /*header*/

        .header {
            height: 141px;
            background: #FFFFFF;
            box-sizing: border-box;
            box-shadow: 0px -1px 0px 0px #F0F2F5;
            display: flex;
            flex-direction: column;
            flex-shrink: 0;

            .header-title {
                border-bottom: 1px solid #EBEEF5;
                font-size: 16px;
                font-family: PingFangSC-Medium, PingFang SC;
                font-weight: 500;
                color: #333333;
                height: 56px;
                position: relative;
                display: flex;
                align-items: center;
                padding: 0 32px;
            }
            .header-content {
                flex: 1;
                padding: 0 32px;
                display: flex;
                align-items: center;
            }
        }
        .bg-line {
            height: 12px;
            background: #F0F2F5;
        }

        // 表格
        .data-table {
            ::-webkit-scrollbar {
                width: 6px;
                height: 6px;
            }
            // 操作按钮
            .option-btn-group {
                .el-button {
                    margin-left: 0;
                    margin-right: 10px;
                }
            }
        }

        /*商品列表*/
        .goods-wrapper {
            padding-bottom: 82px;
            .table-item {
                margin: 16px 0;
                height: 50px;
                display: flex;
                align-items: center;
                justify-content: center;
                &.sku {
                    display: -webkit-box;
                    -webkit-box-orient: vertical;
                    overflow: hidden;
                    -webkit-line-clamp: 2;
                }
            }
            .goods-info {
                display: flex;
                align-items: center;
                .goods-cover {
                    width: 68px;
                    height: 68px;
                    cursor: pointer;
                    margin-right: 16px;
                    flex-shrink: 0;
                }
                .info {
                    display: flex;
                    flex-direction: column;
                    justify-content: space-between;
                    font-size: 12px;
                    font-family: PingFangSC-Regular, PingFang SC;
                    font-weight: 400;
                    color: #333333;
                    .goods-info__title {
                        font-size: 14px;
                        display: -webkit-box;
                        -webkit-box-orient: vertical;
                        overflow: hidden;
                        -webkit-line-clamp: 2;
                    }
                }
            }
        }

        /*空状态*/
        .empty-view {
            flex: 1;
            background: #fff;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            margin-top: 12px;
            .empty-img {
                width: 256px;
                img {
                    width: 100%;
                }
            }
            .empty-text {
                font-size: 14px;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                color: #999999;
                line-height: 20px;
                margin-top: 16px;
            }
        }

        /* 分页 */

        .pagination-wrapper {
            padding: 12px 24px;
            .el-pagination {
                float: right;
                padding: 0;
                background-color: transparent;
            }
        }
    }
    /deep/ .el-dialog__header {
        padding-top: 10px;
        box-shadow:0 1px 0 0 rgba(233,233,233,1);
        display: flex;
        align-items: center;
        background: #FAFAFA;
        border-radius: 4px 4px 0 0;
        .el-dialog__title {
            font-weight: 500;
            color: #333;
            font-size: 14px;
        }
        .el-icon-close:before {
            color: rgb(194,194,194);
            font-size: 17px;
            font-weight: bold;
        }
        .el-dialog__headerbtn {
            top: 14px;
        }
    }
    /deep/ .el-textarea__inner {
        resize: none;
    }
    /deep/ .el-form-item__error {
        padding-top: 0;
    }
    /deep/ .el-form-item {
        margin-bottom: 12px;
    }
}
</style>
<style lang="less">
.wrapper.group-goods-add {
    .el-table {
        th {
            background: #f2f2f2!important;
        }
    }
}
</style>
